<template>
    <div class="login-view">
        <div class="login-content">
            <el-form class="login-form" :model="loginForm" status-icon :rules="rules" ref="loginForm" label-width="100px"
                     @keyup.enter.native="submitForm('loginForm')">
                <div class="login-brand">
                    <div>Login to Chat</div>
                </div>
                <el-form-item label="Terminal" prop="userName" v-show="false">
                    <el-input type="terminal" v-model="loginForm.terminal" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="Username" prop="userName">
                    <el-input type="text" v-model="loginForm.userName" autocomplete="off" placeholder="Username"></el-input>
                </el-form-item>
                <el-form-item label="Password" prop="password">
                    <el-input 
                      :type="showPassword ? 'text' : 'password'"
                      v-model="loginForm.password"
                      autocomplete="off"
                      placeholder="Password"
                    >
                        <template #suffix>
                            <i
                              :class="showPassword ? 'el-icon-view' : 'el-icon-view'"
                              style="cursor: pointer; color: #c0c4cc;"
                              @mouseover="e => e.target.style.color = '#409EFF'"
                              @mouseout="e => e.target.style.color = '#c0c4cc'"
                              @click="showPassword = !showPassword"
                            ></i>
                        </template>
                    </el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="submitForm('loginForm')">Login</el-button>
                    <el-button @click="resetForm('loginForm')">Clear</el-button>
                </el-form-item>
                <div class="register">
                    <router-link to="/register">No account? Go to register</router-link>
                </div>
            </el-form>
        </div>
    </div>
</template>

<script>
import Icp from '../components/common/Icp.vue'
import CryptoJS from 'crypto-js'

export default {
	name: "login",
	components: {
		Icp
	},
	data() {
		var checkUsername = (rule, value, callback) => {
			if (!value) {
				return callback(new Error('Please enter your username'));
			}
			callback();
		};
		var checkPassword = (rule, value, callback) => {
			if (value === '') {
				callback(new Error('Please enter your password'));
			}
			callback();

		};
		return {
			loginForm: {
				terminal: this.$enums.TERMINAL_TYPE.WEB,
				userName: '',
				password: ''
			},
            showPassword: false,
			rules: {
				userName: [{
					validator: checkUsername,
					trigger: 'blur'
				}],
				password: [{
					validator: checkPassword,
					trigger: 'blur'
				}]
			}
		};
	},
	methods: {
		submitForm(formName) {
			this.$refs[formName].validate((valid) => {
				if (valid) {
          const psha256 = CryptoJS.SHA256(this.loginForm.password).toString()

          this.$http({
						url: "/login",
						method: 'post',
						data: 						{
              "terminal": 0,
              "userName": this.loginForm.userName,
              "password": psha256,
            //   "password": this.loginForm.password
            }
					})
						.then((data) => {
							// Save password to cookie (not secure)
							this.setCookie('username', this.loginForm.userName);
							this.setCookie('password', this.loginForm.password);
							// Save token
							sessionStorage.setItem("accessToken", data.accessToken);
							sessionStorage.setItem("refreshToken", data.refreshToken);
              sessionStorage.setItem("code", data.code);
              sessionStorage.setItem("psha256", psha256);

							this.$message.success("Login successful");
							this.$router.push("/home/chat");
						})

				}
			});
		},
		resetForm(formName) {
			this.$refs[formName].resetFields();
		},
		getCookie(name) {
			let reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
			let arr = document.cookie.match(reg)
			if (arr) {
				return unescape(arr[2]);
			}
			return '';
		},
		setCookie(name, value) {
			document.cookie = name + "=" + escape(value);
		}

	},
	mounted() {
		this.loginForm.userName = this.getCookie("username");
		// Storing password in cookie is not secure, just for convenience temporarily
		this.loginForm.password = this.getCookie("password");
	}
}
</script>

<style scoped lang="scss">
.login-view {
    width: 100%;
    height: 100vh;
    background: #f1f3f4; 
    display: flex;
    justify-content: center;
    align-items: center;

   .login-content {
        width: auto;

       .login-form {
            width: 400px;
            background: white;
            border-radius: 8px;
            box-shadow: 0 1px 3px rgba(0, 0, 0, 0.12), 0 1px 2px rgba(0, 0, 0, 0.24);
            padding: 40px;

           .login-brand {
                display: flex;
                justify-content: center;
                align-items: center;
                font-size: 24px;
                font-weight: 500;
                margin-bottom: 30px;
                color: #202124; 
            }

           .el-form-item {
                margin-bottom: 20px;
            }

           .el-form-item__label {
                color: #202124;
                font-size: 14px;
            }

           .el-input__inner {
                border-radius: 4px;
                border: 1px solid #dadce0;
                padding: 10px 12px;
                font-size: 14px;

                &:focus {
                    border-color: #1a73e8; 
                    box-shadow: 0 0 0 3px rgba(26, 115, 232, 0.2);
                }
            }

           .el-button {
                border-radius: 4px;
                padding: 10px 24px;
                font-size: 14px;
                font-weight: 500;

                &.el-button--primary {
                    background-color: #1a73e8;
                    border-color: #1a73e8;

                    &:hover {
                        background-color: #1765cc;
                        border-color: #1765cc;
                    }
                }
            }

           .register {
                margin-top: 20px;
                text-align: right;

                a {
                    color: #1a73e8;
                    text-decoration: none;

                    &:hover {
                        text-decoration: underline;
                    }
                }
            }
        }
    }
}
</style>